﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using VendorExpenses.Model;
using VendorExpenses.Context;
using VendorExpenses.Context.Migrations;
using System.Data.Entity;
using MongoDB.Driver;

namespace XMLReaderAndWriter
{
    public class XMLVendorExpensesLoader
    {
        public static void LoadExpensesFromXML(string fileName)
        {
            // SQL Server connection
            Database.SetInitializer(new MigrateDatabaseToLatestVersion<VendorExpensesContext, Configuration>());
            VendorExpensesContext sqlServerDB = new VendorExpensesContext();

            // MongoDB connecton
            var mongoClient = new MongoClient("mongodb://localhost/");
            var mongoServer = mongoClient.GetServer();
            var expensesDB = mongoServer.GetDatabase("expensesDB");
            var vendors = expensesDB.GetCollection<Vendor>("vendors");

            XDocument xdoc = XDocument.Load(fileName);

            int vendorsCount = (from v in sqlServerDB.Vendors select v).Count();
            var sellers = from s in xdoc.Descendants("sale")
                          select new
                          {
                              VendorName = s.Attribute("vendor").Value,
                              Expenses = s.Descendants("expenses")
                          };

            foreach (var seller in sellers)
            {
                List<Expense> theExpenses = new List<Expense>();

                sqlServerDB.Vendors.Add(new Vendor { VendorName = seller.VendorName });
                sqlServerDB.SaveChanges();
                vendorsCount++;

                foreach (var expense in seller.Expenses)
                {
                    var vendorExpense = new Expense
                    {
                        ExpenseDate = expense.Attribute("month").Value,
                        ExpenseSum = double.Parse(expense.Value),
                        VendorId = vendorsCount
                    };

                    sqlServerDB.Expenses.Add(vendorExpense);
                    theExpenses.Add(vendorExpense);
                }

                sqlServerDB.SaveChanges();

                var vendor = new Vendor
                {
                    VendorName = seller.VendorName,
                    Expenses = theExpenses
                };

                vendors.Insert(vendor);
            }
        }

        public static void LoadExpensesIntoSQLServer(string fileName)
        {
            Database.SetInitializer(new MigrateDatabaseToLatestVersion<VendorExpensesContext, Configuration>());

            VendorExpensesContext sqlServerDB = new VendorExpensesContext();
            using (XmlReader reader = XmlReader.Create(fileName))
            {
                int vendorsCount = (from v in sqlServerDB.Vendors select v).Count();

                while (reader.Read())
                {
                    if ((reader.NodeType == XmlNodeType.Element) && (reader.Name == "sale"))
                    {
                        var vendor = new Vendor
                        {
                            VendorName = reader.GetAttribute("vendor")
                        };

                        sqlServerDB.Vendors.Add(vendor);
                        sqlServerDB.SaveChanges();
                        vendorsCount++;
                    }
                    else if ((reader.NodeType == XmlNodeType.Element) && (reader.Name == "expenses"))
                    {
                        var expense = new Expense
                        {
                            ExpenseDate = reader.GetAttribute("month"),
                            ExpenseSum = double.Parse(reader.ReadInnerXml()),
                            VendorId = vendorsCount
                        };

                        sqlServerDB.Expenses.Add(expense);
                    }

                    sqlServerDB.SaveChanges();
                }
            }
        }

        public static void LoadExpensesIntoMongoDB(string fileName)
        {
            var mongoClient = new MongoClient("mongodb://localhost/");
            var mongoServer = mongoClient.GetServer();
            var expensesDB = mongoServer.GetDatabase("expensesDB");

            var vendors = expensesDB.GetCollection<Vendor>("vendors");

            XDocument xdoc = XDocument.Load(fileName);

            var sellers = from s in xdoc.Descendants("sale")
                          select new
                          {
                              VendorName = s.Attribute("vendor").Value,
                              Expenses = s.Descendants("expenses")
                          };

            foreach (var seller in sellers)
            {
                List<Expense> theExpenses = new List<Expense>();

                foreach (var expense in seller.Expenses)
                {
                    var vendorExpense = new Expense
                    {
                        ExpenseDate = expense.Attribute("month").Value,
                        ExpenseSum = double.Parse(expense.Value)
                    };

                    theExpenses.Add(vendorExpense);
                }

                var vendor = new Vendor
                {
                    VendorName = seller.VendorName,
                    Expenses = theExpenses
                };

                vendors.Insert(vendor);
            }
        }
    }
}
